import { createStore } from 'vuex'
import createPersistedState from "vuex-persistedstate";
export default createStore({
  state: {
    token:"",
    navright:"登录",
    tabbar:false,
    saverouter:"index",
    cartdata:[],
    userInfo:{}
  },
  mutations: {
    logout(state){
      state.token=""
      state.cartdata=[]
      state.userInfo={}
    },
    setuser(state,data){
      state.userInfo=data
    },
    channavright(state,data){
      state.navright=data
    },
    chantrydarta(state,data){
      state.trydarta=data
    },
    chantrytabbar(state,data){
      state.tabbar=data
    },
    chanttoken(state,data){
      state.token=data
    },
    chantsaverouter(state,data){
      state.saverouter=data
    },
    chantcartstatus(state,data){
     
    },
    delecart(state,id){
      state.cartdata =state.cartdata.filter( item => item.id !== id)
    }
    ,
    addcartdata(state,data){
      let index = state.cartdata.findIndex(item => item.id === data.id)
      index == -1 ?  state.cartdata.unshift(data) : state.cartdata[index].num +=data.num
    },
    delebought(state){
      state.cartdata =state.cartdata.filter( item => !item.selected )
   
    }

  },
  actions: {
  },
  modules: {
  },
  getters: {
    gettoken(state){
      return state.token;
    },
    getnavright(state){
      return state.navright;
    },
    gettrydarta(state){
      return state.trydarta;
    },
    gettabbar(state){
      return state.tabbar;
    },
    getsaverouter(state){
      return state.saverouter;
    },
    getcartsum(state){
      let sum =0
      // return state.cartdata.reduce((total , item ) => total.num +=item.num)
      state.cartdata.forEach(item =>  sum += item.num)
      return sum
      
    },
    carttotalPrice(state){
      let sum=0
      state.cartdata.forEach(({num,selected,price}) =>  selected && (sum += num *price))
      return sum
    },
    getcarttotal(state){
      return state.cartdata
    },
    getnumber(state){
      let totalnum=0
     state.cartdata.forEach(({num,selected}) =>  selected && (totalnum += num))
     return totalnum
    },
    getgoods_ids(state){
      let arr=[]
      state.cartdata.forEach( ({ id ,selected}) => selected && ( arr.push(id)  ) )
      return arr
    }



  },
   plugins: [createPersistedState()],
  
})
